import { Toolkit } from "../../Framework/scripts/Toolkit";
import Watcher from "../../Framework/scripts/Watcher";
import Drop from "../Drop";
import CanDrag from "./CanDrag";
import UploadHelper from "./upload/UploadHelper";

const { ccclass, property } = cc._decorator;


@ccclass
export default class Editor extends cc.Component {

    @property(cc.Node)
    center: cc.Node = null;

    @property([cc.Node])
    centerlayers: cc.Node[] = [];
    @property(cc.Label)
    layerTip: cc.Label;
    current = 0;

    @property(cc.Node)
    uploadWindow: cc.Node;


    public static instance: Editor = null;
    onLoad() {
        Editor.instance = this;
    }

    start() {
        this.initEditorStyle();
        this.initGraphics();
        this.addEvent();
    }
    public static readonly SET_CONFIG = "SET_CONFIG";
    upload() {
        this.uploadWindow.active = true;
        UploadHelper.show(this);
    }
    uploadCallback(config: any) {
        this.uploadWindow.active = false;
        //Watcher.dispatch(Editor.SET_CONFIG,config);

        for (let l of this.centerlayers) {
            for (let e of l.children) {
                e.getComponent(Drop).clearIcon();
            }
        }

        this.count_table = {};
        let custom = config[0];
        for (let i = 0; i < custom.layers.length; i++) {
            let layer = custom.layers[i];
            let node = this.centerlayers[i];
            for (let item of layer) {
                let dp = node.children[item.index].getComponent(Drop);
                dp.setIcon(item.gid);
            }
        }
    }

    count_table = {};
    //下载配置
    save_config() {

        //验证
        let msg = "";
        for (let k in this.count_table) {
            if (this.count_table[k] % 3 !== 0) {
                msg += `item ${k} 当前数量: {${this.count_table[k]}},不是三的倍数 无法完成消除\n`;
            }
        }
        if (msg !== "") {
            alert(msg);
            return;
        }

        //输出配置
        let customConfig = {};
        let config = customConfig[0] = {};
        config.type = 'custom';
        config.layers = [];
        let i = 0;
        for (let layer of this.centerlayers) {

            for (let j = 0; j < layer.childrenCount; j++) {
                let e = layer.children[j];
                let dp = e.getComponent(Drop);
                if (dp && dp.gid !== "") {
                    let item = {
                        x: dp.node.x + layer.x,
                        y: dp.node.y + layer.y,
                        gid: dp.gid,
                        index: j
                    };
                    if (!config.layers[i])
                        config.layers[i] = [];
                    config.layers[i].push(item);
                }
            }
            ++i;
        }

        Toolkit.saveForBrowser(JSON.stringify(customConfig), "customConfig.json");
    }

    // isShowGrid = true;
    // switchGirdBg(){
    //     this.isShowGrid = !this.isShowGrid;

    //     for(let l of this.centerlayers){
    //         let dps = l.getComponentsInChildren(Drop);
    //         for(let dp of dps){
    //             dp.node.active = this.isShowGrid && dp.gid === "";
    //         }
    //     }

    // }

    initEditorStyle() {

        //鼠标样式
        // const cursor_icon_url = '/res/import/11/11adf5f9-be90-4765-b3f2-94ea4993bf71.png';
        // const url = `url('${cursor_icon_url}'),auto`;
        // cc.game.canvas.style.cursor = url;


    }

    gfx: cc.Graphics = null;
    initGraphics() {
        cc.view.enableAntiAlias(true);
        const gfx = this.gfx = this.node.addComponent(cc.Graphics);

    }

    guide(node: cc.Node) {
        const gfx = this.gfx;
        gfx.clear();
        let _x = this.center.x;
        let _y = this.center.y;
        gfx.strokeColor = cc.Color.RED;
        gfx.lineWidth = 2;

        for (let n of this.center.children) {
            if (n.name != node.name) {
                gfx.moveTo(_x + node.x, _y + node.y);

                let dif = n.getPosition().subSelf(node.getPosition()).normalizeSelf();
                let center = dif.rotateSelf(cc.macro.RAD * 30 * dif.x === 0 ? 0 : dif.x > 0 ? -1 : 1).mulSelf(100).addSelf(node.getPosition());
                gfx.bezierCurveTo(_x + node.x, _y + node.y, center.x, center.y, _x + n.x, _y + n.y);
                //gfx.lineTo(n.x, n.y);
            }
        }
        gfx.stroke();

        this.drawGrid();
    }

    drawNode(r: cc.Node, x = 0, y = 0) {
        const gfx = this.gfx;
        if (!gfx) return;

        let size = cc.winSize;
        let w = Toolkit.Clamp(r.width, 2, size.width - 20);
        let h = Toolkit.Clamp(r.height, 2, size.height - 20);
        gfx.roundRect(r.x - w * r.anchorX + x, r.y - h * r.anchorY + y, w, h, 4);
        gfx.stroke();
    }

    drawRoad() {
        const gfx = this.gfx;
        gfx.strokeColor = cc.Color.RED;
        gfx.lineWidth = 4;

        // for (let i = 0; i < list.length; i++) {

        //     let curren = list[i];
        //     let next = list[(i + 1) % list.length];

        //     gfx.moveTo(curren.x, curren.y);
        //     gfx.lineTo(next.x, next.y);
        // }
        // gfx.stroke();
    }

    drawGrid() {
        const gfx = this.gfx;
        gfx.strokeColor = cc.Color.WHITE;
        gfx.lineWidth = 2;
        let offsetX = this.center.x;
        let offsetY = this.center.y;

        for (let n of this.center.children) {
            this.drawNode(n, offsetX, offsetY);
        }
    }

    addEvent() {

    }

    switchLayer() {
        this.current = (this.current + 1) % this.centerlayers.length;
        this.center = this.centerlayers[this.current];
        this.layerTip.string = `第 ${this.current + 1} 层`;
        //关闭顶层
        for (let i = this.current + 1; i < this.centerlayers.length; i++) {
            this.centerlayers[i].active = false;
        }
        //屏蔽底层
        for (let i = 0; i < this.current; i++) {
            let elements = this.centerlayers[i].children;
            for (let e of elements) {
                e.getComponent(Drop).interaction = false;
            }
        }
        //显示当前层
        this.center.active = true;
        for (let e of this.center.children) {
            e.getComponent(Drop).interaction = true;
        }
    }


    //#region  KEYBOARD EVENT
    onEnable() {
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
    }

    onDisable() {
        cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
    }

    onKeyDown(event) {

        Toolkit.logTrace(`keyDown: ${event.keyCode}`);
        if (this.currentSeletedObj) {
            if (event.keyCode > 48 && event.keyCode < 55) {
                this.currentSeletedObj.setIcon(`0${event.keyCode - 48}`);
            }
            // switch (event.keyCode) {
            //     case cc.macro.KEY.num1:
            //         this.currentSeletedObj.setIcon('01');
            //         break;
            //     default:
            //         return;
            // }
        }

    }

    currentSeletedObj = null;
    heroSkin: string = null;

    touchEvent(e: cc.Event.EventTouch) {

        if (this.currentSeletedObj == e.currentTarget) return;
        this.currentSeletedObj = e.currentTarget;
        //选中边框
        this.drawNode(e.currentTarget);

    }

}



